package com.ayu.a.practice01;

/**
 * @Author 徐林玉
 * @Description MaxProfitPrac
 * @Date 2022/11/8 10:57
 * @Version 1.0
 */
public class MaxProfitPrac {

    public static void main(String[] args) {

        int[] arr = new int[]{1, 3, 2, 4, 7, 8};

        int total = maxProfit(arr);

        System.out.println("total = " + total);

    }


    public static int maxProfit(int[] arr) {


        if (arr == null || arr.length == 0) {

            return 0;
        }

        int index = 0;
        int total = 0;
        int length = arr.length;

        while (index < length) {

            while (index < length - 1 && arr[index] > arr[index + 1]) {

                index++;
            }

            int min = arr[index];

            while (index < length - 1 && arr[index] < arr[index + 1]) {

                index++;
            }
            total += arr[index++] - min;

        }


        return total;

    }


    public static int maxProfit2(int[] arr) {


        if (arr == null || arr.length < 2) {

            return 0;
        }

        int length = arr.length;

        int[][] dp = new int[length][2];

        //初始条件
        dp[0][0] = 0;

        dp[0][1] = -arr[0];
        for (int i = 1; i < length; i++) {
            //第i天手上没有股票：
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + arr[i]);
            //第i天手上有股票
            dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - arr[i]);

        }


        //最后一天手上肯定没有股票
        return dp[length - 1][0];
    }
}
